import React, { Component, useState, useEffect, useRef } from 'react'
import './index.scss'
import { Tabs, Form, Input, Button, Checkbox, message } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { reg } from '../../utils/validate'
import { request } from '../../api'
import { withRouter } from 'react-router-dom'
import { hashHistory } from '../../utils'

const { TabPane } = Tabs
const { phone, pwd } = reg
export default class LoginCom extends Component {
    render() {
        return (
            <div className='login'>
                <div className="login-box">
                    <Tabs
                        defaultActiveKey="1"
                        centered
                        animated
                    >
                        <TabPane
                            tab="密码登录"
                            key="1"
                        >
                            <PassLogin history={this.props.history} />
                        </TabPane>


                        <TabPane
                            tab="验证码登录"
                            key="2"
                        >
                            <CptLogin history={this.props.history} />
                        </TabPane>
                    </Tabs>
                </div>
            </div>
        )
    }
}

// @withRouter    //向props注入match history location
class PassLogin extends Component {
    componentDidMount() {
        if (localStorage.remember && localStorage.getItem('userinfo')) {
            var userinfo = JSON.parse(localStorage.getItem('userinfo'))
            this.passLogin.setFieldsValue({ ...userinfo, remember: localStorage.remember })
        }
    }
    onFinish = (v) => {
        request.login(v)
            .then(res => {
                if (res.code === 200) {
                    // console.log(res);
                    localStorage.setItem('userinfo', JSON.stringify(res.result))
                    localStorage.setItem('token', res.token)
                    localStorage.setItem('remember', v.remember ? v.remember : '')
                    console.log(this);
                    this.props.history.push('./main')
                    // history.push('./main')
                }
            })
            .catch(err => {
                console.log(err);
            })
    }
    onFinishFailed = () => {
        message.error('Wrong phone or password!')
    }
    render() {
        return (
            <div>

                <Form
                    wrapperCol={{ offset: 4, span: 16 }}
                    scrollToFirstError
                    name="pass-login"
                    className="login-form"
                    initialValues={{
                        remember: false,
                    }}
                    onFinish={this.onFinish}
                    onFinishFailed={this.onFinishFailed}
                    ref={el => this.passLogin = el}
                >
                    <Form.Item
                        name="phone"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your Phone number!',
                            },
                            {
                                pattern: phone, message: 'The phone is illegal!'
                            }
                        ]}
                    >
                        <Input
                            prefix={
                                <UserOutlined
                                    className="site-form-item-icon"
                                />
                            }
                            placeholder="Phone"
                        />
                    </Form.Item>
                    <Form.Item
                        name="password"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your Password!',
                            },
                            {
                                pattern: pwd, message: 'Password is not valid'
                            }
                        ]}
                    >
                        <Input.Password
                            prefix={
                                <LockOutlined
                                    className="site-form-item-icon"
                                />
                            }
                            placeholder="Password"
                        />
                    </Form.Item>
                    <Form.Item>
                        <Form.Item
                            name="remember"
                            valuePropName="checked"
                            noStyle
                        >
                            <Checkbox>记住密码</Checkbox>
                        </Form.Item>


                    </Form.Item>

                    <Form.Item>
                        <Button
                            block
                            type="primary"
                            htmlType="submit"
                            className="login-form-button"
                        >
                            登录
                        </Button>

                    </Form.Item>
                </Form>
            </div >
        )
    }
}

function CptLogin({ history }) {
    const [flag, setFlag] = useState(false)
    const [btnShow, setBtnShow] = useState(true)
    let [count, setCount] = useState(10)
    const cptForm = useRef()
    //捕捉异常

    const flagChange = (v) => {
        // console.log(cptForm.current);
        v = v.target.value
        console.log(v);
        phone.test(v) ? setFlag(true) : setFlag(false)
    }
    const onFinish = (v) => {
        console.log(v);
    }
    let timer = null
    const sendCpt = () => {
        request.sendCpt(cptForm.current)
            .then(() => {
                setBtnShow(false)
                timer = setInterval(() => {
                    setCount(--count)
                    if (count <= 0) {
                        clearInterval(timer)
                        timer = null
                        setCount(10)
                        setBtnShow(true)
                    }
                }, 1000)
            })
    }
    useEffect(() => {
        if (localStorage.getItem('userinfo')) {
            var userinfo = JSON.parse(localStorage.getItem('userinfo'))
            CptLogin.current.setFieldsValue({
                phone: userinfo.phone
            })
        }
        return () => {

        }
    }, [])
    return (
        <div>

            <Form
                wrapperCol={{ offset: 4, span: 16 }}
                scrollToFirstError
                name="cpt-login"
                className="login-form"
                ref={CptLogin}
                initialValues={{
                    remember: true,
                }}
                onFinish={onFinish}
            >
                <Form.Item
                    name="phone"
                    rules={[
                        {
                            required: true,
                            message: 'Please input your Phone number!',
                        },
                        {
                            pattern: phone, message: 'The phone is illegal!'
                        }
                    ]}
                >
                    <Input
                        prefix={
                            <UserOutlined
                                className="site-form-item-icon"
                            />
                        }
                        onChange={flagChange}
                        placeholder="Phone"
                    />
                </Form.Item>
                <Form.Item
                    rules={[
                        {
                            required: true,
                            message: 'Captcha is required!',
                        }
                    ]}
                >
                    <Input
                        name="captcha"
                        prefix={
                            <LockOutlined
                                className="site-form-item-icon"
                            />
                        }
                        addonAfter={
                            btnShow ? <Button
                                disabled={!flag}
                                onClick={sendCpt}
                            >Send</Button> : <Button
                                disabled
                                block
                            >{count} S</Button>
                        }

                        maxLength="4"
                        placeholder="Captcha"
                    />
                </Form.Item>

                <Form.Item>
                    <Button
                        block
                        type="primary"
                        htmlType="submit"
                        className="login-form-button"
                    >
                        登录
                    </Button>

                </Form.Item>
            </Form>
        </div >
    )
}